#!/usr/bin/env python3
import os 
import shutil
import sys
import re

def save_code_as_normal()->bool:
    src_path:str = os.path.abspath("run/code.cpp")
    id:int = peek_code_for_id(src_path)
    if(id == -1):
        return False
    dst_path:str = os.path.abspath(f"code/code{id}.cpp")
    if not os.path.exists(src_path):
        print("No code.cpp file found")
        return False
    if os.path.exists(dst_path):
        print(f"Code{id}.cpp already exists")
        return False
    shutil.copyfile(src_path, dst_path)
    print(f"Code{id}.cpp saved successfully")
    return True

def save_code_as_competition()->bool:
    src_path:str = os.path.abspath("run/code.cpp")
    id:int = peek_code_for_id(src_path)
    if(id == -1):
        return False
    dst_path:str = os.path.abspath(f"code/competion/code{id}.cpp")
    if not os.path.exists(src_path):
        print("No code.cpp file found")
        return False
    if os.path.exists(dst_path):
        print(f"Code{id}.cpp already exists")
        return False
    shutil.copyfile(src_path, dst_path)
    print(f"Code{id}.cpp saved successfully")
    return True

def copy_template_code()->bool:
    src_path:str = os.path.abspath("code.cpp")
    if not os.path.exists(src_path):
        print("No template code.cpp file found")
        return False
    dst_path:str = os.path.abspath("run/code.cpp")
    shutil.copyfile(src_path, dst_path)
    print("Template code copied successfully")
    return True

def peek_code_for_id(path:str)->int:
    if not os.path.exists(path):
        print("No code found")
        return -1
    with open(path, "r", encoding='utf-8') as f:
        code = f.read()
        pattern = r'Code([\d]+)'
        matches = re.findall(pattern, code)
        if matches:
            return int(matches[0])
        else:
            return -1

def main():
    print("Code Saving Tool")
    print("Usage: python3 command.py <normal|competition|template>")
    if len(sys.argv)==1:
        if save_code_as_normal():
            copy_template_code()
        return
    if(len(sys.argv) != 2):
        print("Invalid arguments")
        os.system("pause")
        return
    if(sys.argv[1] == "normal"):
        print("Saving code as normal")
        if save_code_as_normal():
            print("Code saved successfully")
    elif(sys.argv[1] == "competition"):
        print("Saving code as competition")
        if save_code_as_competition():
            print("Code saved successfully")
    elif(sys.argv[1] == "template"):
        print("Copying template code")
        if copy_template_code():
            print("Template code copied successfully")
    else:
        print("Invalid argument")
    os.system("pause")

if __name__ == "__main__":
    main()